<route lang="json5">
{
  layout: 'default',
  style: {
    navigationBarTitleText: '质量科普',
  },
}
</route>

<script lang="ts" setup>
import type { UserCenterGetParams } from '@/service/app/types'
import { userCenterGet4, userCenterGet5 } from '@/service/app/userCenter'

defineOptions({
  name: 'Quality',
})

// 获取屏幕边界到安全区域距离
const { safeAreaInsets } = uni.getSystemInfoSync()

// 分类列表
const categories = ref<any[]>([])
const selectedCategory = ref('')

// 视频列表
const videoList = ref<any[]>([])
const currentPage = ref(1)
const hasMore = ref(true)
const isLoading = ref(false)

// 加载分类列表
async function loadCategories() {
  try {
    const result = await userCenterGet4({
      params: {
        'condition.page': 1,
        'condition.size': 20,
      },
    })
    const apiCategories = result?.data || []

    // 在分类列表最前面添加"全部"选项
    categories.value = [
      {
        id: 'all',
        categoryId: 'all',
        name: '全部',
        title: '全部',
        categoryName: '全部',
      },
      ...apiCategories,
    ]

    if (categories.value.length > 0) {
      // 默认选中"全部"
      selectedCategory.value = 'all'
      // 手动加载第一页视频
      currentPage.value = 1
      hasMore.value = true
      loadVideos()
    }
  }
  catch (error) {
    console.error('加载分类失败:', error)
  }
}

// 加载视频列表
async function loadVideos() {
  if (isLoading.value || !hasMore.value)
    return

  isLoading.value = true
  try {
    const params: UserCenterGetParams = {
      'condition.page': currentPage.value,
      'condition.size': 10,
    }

    // 只有不是"全部"时才传递分类参数
    if (selectedCategory.value && selectedCategory.value !== 'all') {
      params['condition.category'] = selectedCategory.value
    }

    console.log('加载视频参数:', params)
    const result = await userCenterGet5({ params })
    const newVideos = result?.data?.data || []

    if (currentPage.value === 1) {
      videoList.value = newVideos
    }
    else {
      videoList.value.push(...newVideos)
    }

    hasMore.value = newVideos.length === 10
    if (hasMore.value) {
      currentPage.value++
    }
  }
  catch (error) {
    console.error('加载视频失败:', error)
  }
  finally {
    isLoading.value = false
  }
}

// 防抖定时器
let debounceTimer: number | null = null

// 处理分类变化
function handleCategoryChange(categoryId: string) {
  console.log('切换到分类:', categoryId)

  // 清除之前的定时器
  if (debounceTimer) {
    clearTimeout(debounceTimer)
  }

  // 防抖处理
  debounceTimer = setTimeout(() => {
    if (selectedCategory.value !== categoryId) {
      selectedCategory.value = categoryId
      currentPage.value = 1
      hasMore.value = true
      videoList.value = [] // 清空当前列表
      loadVideos()
    }
  }, 100) // 100ms 防抖
}

// 播放视频
function playVideo(video: any) {
  console.log('播放视频:', video)
  uni.showToast({
    title: '视频播放功能开发中',
    icon: 'none',
  })
}

// 获取完整图片URL
function getFullImageUrl(relativePath: string) {
  if (!relativePath)
    return '/static/images/default-avatar.png'
  if (relativePath.startsWith('http'))
    return relativePath
  const ossBaseUrl = 'https://oss.tz-group.com/'
  const cleanPath = relativePath.startsWith('/') ? relativePath.slice(1) : relativePath
  return `${ossBaseUrl}${cleanPath}`
}

// 从文件名获取视频时长（这里简化处理，实际应该从视频元数据获取）
function getVideoDuration(fileName: string) {
  // 这里可以根据实际需求实现，暂时返回固定值
  return '02:30'
}

// 页面触底加载更多
onReachBottom(() => {
  loadVideos()
})

// 页面加载时初始化
onMounted(async () => {
  await loadCategories()
  // loadCategories 内部已经处理了视频加载
})
</script>

<template>
  <view
    class="min-h-screen"
    :style="{
      marginTop: `${safeAreaInsets?.top}px`,
      background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)',
    }"
  >
    <!-- 分类选择器 -->
    <view
      class="sticky top-0 z-10 shadow-sm"
      :style="{ background: 'linear-gradient(to bottom, #E9F0FF, #F2F5F9)' }"
    >
      <wd-tabs
        :model-value="selectedCategory"
        :sticky="false"
        :scrollable="true"
        :show-line="true"
        :ellipsis="true"
        line-height="2px"
        line-color="#3b82f6"
        active-color="#3b82f6"
        inactive-color="#6b7280"
        @change="handleCategoryChange"
      >
        <wd-tab
          v-for="category in categories"
          :key="category.id || category.categoryId"
          :name="category.id || category.categoryId"
          :title="category.name || category.title || category.categoryName"
        />
      </wd-tabs>
    </view>

    <!-- 瀑布流视频列表 -->
    <view class="p-4">
      <view v-if="isLoading && videoList.length === 0" class="py-8 text-center text-gray-500">
        加载中...
      </view>

      <view v-else-if="videoList.length > 0" class="columns-2 gap-4">
        <view
          v-for="(video, index) in videoList"
          :key="video.id || index"
          class="mb-4 break-inside-avoid overflow-hidden rounded-xl bg-white shadow-sm"
          @click="playVideo(video)"
        >
          <!-- 视频封面 -->
          <view class="relative aspect-video bg-gray-200">
            <image
              v-if="video.covers && video.covers.length > 0"
              :src="getFullImageUrl(video.covers[0].attachmentAddress)"
              class="h-full w-full"
              mode="aspectFill"
            />
            <view v-else class="h-full w-full flex items-center justify-center bg-gray-200">
              <text class="i-carbon-play text-4xl text-gray-400" />
            </view>

            <!-- 播放按钮 -->
            <view class="absolute inset-0 flex items-center justify-center bg-black bg-opacity-30">
              <view class="rounded-full bg-white bg-opacity-90 p-3">
                <text class="i-carbon-play text-2xl text-blue-500" />
              </view>
            </view>
          </view>

          <!-- 视频信息 -->
          <view class="p-3">
            <view class="line-clamp-2 mb-2 text-sm text-gray-800 font-medium">
              {{ video.scienceName || '质量科普视频' }}
            </view>
            <view class="mb-2 text-xs text-gray-500">
              {{ video.introduction || '质量相关知识科普' }}
            </view>
            <view class="flex items-center justify-between text-xs text-gray-400">
              <view class="flex items-center space-x-2">
                <text class="i-carbon-view text-sm" />
                <text>{{ video.views || 0 }}</text>
              </view>
              <view class="flex items-center space-x-2">
                <text class="i-carbon-time text-sm" />
                <text>{{ video.uploadTime || '刚刚' }}</text>
              </view>
            </view>
          </view>
        </view>
      </view>

      <!-- 空状态 -->
      <view v-else class="py-12 text-center">
        <text class="i-carbon-video text-6xl text-gray-300" />
        <view class="mt-4 text-gray-500">
          暂无视频内容
        </view>
      </view>

      <!-- 加载更多状态 -->
      <view v-if="videoList.length > 0" class="py-4 text-center">
        <view v-if="isLoading" class="text-gray-500">
          加载中...
        </view>
        <view v-else-if="!hasMore" class="text-sm text-gray-400">
          没有更多了
        </view>
      </view>
    </view>

    <!-- 底部信息 -->
    <FgFooter />
  </view>
</template>
